package cn.uikit.demo.widget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import sivin.uikit.utils.dp

class OverlappingView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private var bitmapA: Bitmap? = null
    private var bitmapB: Bitmap? = null
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val rectF = RectF(0f, 0f, 0f, 0f)

    private var progress = 0.3f

    private val diff = 6f.dp

    fun setBitmaps(bitmapA: Bitmap, bitmapB: Bitmap) {
        this.bitmapA = bitmapA
        this.bitmapB = bitmapB
        invalidate() // 刷新视图
    }

    fun setProgress(progress: Float) {
        this.progress = progress
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = width.toFloat()
        val height = height.toFloat()

        rectF.set(0f, 0f, width, height)

        // 绘制 A 的上半部分
        bitmapA?.let {
            canvas.save()
            canvas.clipRect(0f, 0f, width, height) // 限制为上半部分
            canvas.drawBitmap(it, null, rectF, paint)
            canvas.restore()
        }

        val bottomStart = (height - diff * 2) * (1.0f - progress) + diff
        // 绘制 B 的下半部分
        bitmapB?.let {
            canvas.save()
            canvas.clipRect(0f, bottomStart, width, height) // 限制为下半部分
            canvas.drawBitmap(it, null, rectF, paint)
            canvas.restore()
        }
    }
}